//
//  CLBaseViewController.m
//  chanlin
//
//  Created by Ryan on 14-11-1.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLBaseViewController.h"
#import "IFAlertView.h"
#import "SgrGCD.h"
#import "CLComentDataModel.h"
#import "CLShareViewController.h"
#import "BlockUI.h"
#import "CLGlobleDataModel.h"
#import "IFMoviePlayerController.h"
#import "Sgr_macro.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "ReadDocHistory.h"

#import "CLSlidersViewController.h"
#import "CLDocViewController.h"
#import "CLTopicViewController.h"
#import "CLVideoViewController.h"


@interface CLBaseViewController()

@property (nonatomic,strong)CLShareViewController *share;
@property (nonatomic,strong)UIButton *mark;
@property (nonatomic, copy) void (^pickblock)(UIImage*);


@end

@implementation CLBaseViewController


- (instancetype)init{
    self=[super init];
    if(self){
        self.ctrlName=NSStringFromClass([self class]);
        if([self isKindOfClass:[CLSlidersViewController class]]){
            self.ctrlName=@"slides";
        }else if([self isKindOfClass:[CLDocViewController class]]){
            self.ctrlName=@"doc";
        }else if([self isKindOfClass:[CLTopicViewController class]]){
            self.ctrlName=@"topic";
        }else if([self isKindOfClass:[CLVideoViewController class]]){
            self.ctrlName=@"video";
        }
    }
    return self;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick beginLogPageView:_isStrNotNull(self.itemId)?[NSString stringWithFormat:@"%@_%@",self.ctrlName,self.itemId]:self.ctrlName];
}

- (void)viewWillDisappear:(BOOL)animated{
    [MobClick endLogPageView:_isStrNotNull(self.itemId)?[NSString stringWithFormat:@"%@_%@",self.ctrlName,self.itemId]:self.ctrlName];
}

- (void)dealloc{
    [[CLGloble sharedInstance] clearMovie];
}

- (void)setItemId:(NSString *)itemId{
    _itemId=itemId;
    [[ReadDocHistory shareInstance] readed:itemId];
    
}

- (void)setOnlyItemId:(NSString *)itemId{
    _itemId=itemId;
}


- (void)viewDidLoad{
    [[CLGloble sharedInstance] clearMovie];
}

- (BOOL)__shouldAutorotate{
    return NO;
}

- (NSUInteger)__supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)_showAlertWithTitle:(NSString *)title message:(NSString *)message block:(void(^)(int buttonIndex))block cancelButtonTitle:(NSString *)cancelButtonTitle button1:(NSString *)button1 button2:(NSString *)button2{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:button1,button2, nil];
    if(self.blocks==nil){
        self.blocks=[NSMutableDictionary dictionary];
    }
    [self.blocks sgrSetObject:block forKey:[NSString stringWithFormat:@"%lu",(unsigned long)[alert hash]]];
    
    [alert show];
    
}

- (void)_showAlertWithTitle:(NSString *)title message:(NSString *)message block:(void(^)(int buttonIndex))block cancelButtonTitle:(NSString *)cancelButtonTitle confirmButtonTitles:(NSString *)confirmButtonTitles{
    

    if (AtLeastIOS8)
    {
        UIAlertController *alert=[UIAlertController alertControllerWithTitle:title
                                                                     message:message
                                                              preferredStyle:UIAlertControllerStyleAlert];
        if(cancelButtonTitle){
            UIAlertAction *action=[UIAlertAction actionWithTitle:cancelButtonTitle
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction *action){
                                                             
                                                             if(block)
                                                                 block(0);
                                                             
                                                         }];
            [alert addAction:action];
        }
        
        if(confirmButtonTitles){
            UIAlertAction *action=[UIAlertAction actionWithTitle:confirmButtonTitles
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction *action){
                                                             if(block)
                                                                 block(1);
                                                             
                                                             
                                                         }];
            [alert addAction:action];
        }
        [[self k_rootController] presentViewController:alert animated:YES completion:nil];
        
    }else{
        IFAlertView *alert=[[IFAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle confirmButtonTitles:confirmButtonTitles];
        
        if(block){
            if(self.blocks==nil){
                self.blocks=[NSMutableDictionary dictionary];
            }
            NSString *alertHash = [NSString stringWithFormat:@"%lu",(unsigned long)[alert hash]];
            [self.blocks sgrSetObject:block forKey:alertHash];
        }
        
        
        [alert show];
    }
    
    
    
    
}
- (void)openComment:(NSString *)topicId comfirmPress:(void (^)(NSString *cont,int select))block{
    self.isInputShow=YES;
    InputView *input=[[InputView alloc] init];
    self.inputView=input;
    input.comfirmPress=block;
    [self.inputView createContent:nil];
    [self.view addSubview:self.inputView];
    [self.view bringSubviewToFront:self.inputView];
    [self.inputView notResign];
    self.inputView.isShowShare=NO;
    self.inputView.hidden=NO;
    
}


- (void)openComment:(NSString *)topicId replayId:(NSString *)replayId backString:(NSString *) str block:(void (^)(BOOL success,NSString *commentId))block{
    self.isInputShow=YES;
    InputView *input=[[InputView alloc] init];
    self.isShareShow=NO;
    input.isShowShare=NO;
   // self.inputView.backString=str;
    self.inputView=input;
    __weak typeof(self) me=self;
    input.comfirmPress=^(NSString *content,int select){
        if(_isStrNULL(content)){
            [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论数据不能为空"];
        }
        
        if([content length]>300){
            [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论不能超过300个字"];
        }
        NSString *content2=[NSString stringWithFormat:@"%@#$%@",content,str];
        
        if([[CLGloble sharedInstance] isLogin]){
            [[CLComentDataModel sharedInstance] submitComment:topicId
                                                      content:content2
                                                      replyID:replayId
                                                        block:^(BOOL success, NSString *commentId) {
                                                            if (success) {
                                                                [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"评论成功"];
                                                                [me.inputView resign];
                                                                if(block){
                                                                    block(success,commentId);
                                                                }
                                                            }else{
                                                                [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论失败"];
                                                            }
                                                        }];
        }else{
            [[CLComentDataModel sharedInstance] anonymousSubmitCommentWithTopicId:topicId
                                                                          content:content
                                                                          replyID:replayId
                                                                            block:^(BOOL success, NSString *commentId) {
                                                                                if (success) {
                                                                                    [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"评论成功"];
                                                                                    [me.inputView resign];
                                                                                    if(block){
                                                                                        block(success,commentId);
                                                                                    }
                                                                                }else{
                                                                                    [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论失败"];
                                                                                }
                                                                            }];
        }
        
        self.isInputShow=NO;
    };
    [self.inputView createContent:nil];
    [self.view addSubview:self.inputView];
    [self.inputView notResign];

}


- (void)openComment:(NSString *)topicId replayId:(NSString *)replayId block:(void (^)(NSString *cont,int select))block{
    self.isInputShow=YES;
    InputView *input=[[InputView alloc] init];
    self.isShareShow=YES;
    input.isShowShare=YES;
    self.inputView=input;
    __weak typeof(self) me=self;
    input.comfirmPress=^(NSString *content,int select){
        if(_isStrNULL(content)){
            [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论数据不能为空"];
        }
        
        if([content length]>300){
            [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论不能超过300个字"];
        }
        
        if([[CLGloble sharedInstance] isLogin]){
            [[CLComentDataModel sharedInstance] submitComment:topicId
                                                      content:content
                                                      replyID:replayId
                                                        block:^(BOOL success, NSString *commentId) {
                                                            if (success) {
                                                                [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"评论成功"];
                                                                [me.inputView resign];
                                                                if(block){
                                                                    block(content,select);
                                                                }
                                                            }else{
                                                                [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论失败"];
                                                            }
                                                        }];
        }else{
            [[CLComentDataModel sharedInstance] anonymousSubmitCommentWithTopicId:topicId
                                                                          content:content
                                                                          replyID:replayId
                                                                            block:^(BOOL success, NSString *commentId) {
                                                                                if (success) {
                                                                                    [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"评论成功"];
                                                                                    [me.inputView resign];
                                                                                    if(block){
                                                                                        block(content,select);
                                                                                    }
                                                                                }else{
                                                                                    [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"评论失败"];
                                                                                }
                                                                            }];
        }
        
        self.isInputShow=NO;
    };
    [self.inputView createContent:nil];
    [self.view addSubview:self.inputView];
    [self.inputView notResign];
}

- (IFToolBarViewController *)showToolbarWithType:(IFActive_ButtomToolBarButtonType) buttomToolBarButtonType{
    
    IFToolBarViewController *tool=[[IFToolBarViewController alloc] init];
    tool.view.frame=CGRectMake(0, GlobleHeight-TOOLBARHEIGH, GlobleWidth, TOOLBARHEIGH);
    [tool addButton:buttomToolBarButtonType];
    tool.view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tool.view];
    [self addChildViewController:tool];
    self.tool=tool;
    return self.tool;
}

- (IFToolBarViewController *)showSliderToolbarWithType:(IFActive_ButtomToolBarButtonType) buttomToolBarButtonType{
    IFToolBarViewController *tool=[[IFToolBarViewController alloc] init];
    tool.isSlider=YES;
    tool.view.frame=CGRectMake(0, GlobleHeight-TOOLBARHEIGH, GlobleWidth, TOOLBARHEIGH);
    [tool addButton:buttomToolBarButtonType];
    tool.view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tool.view];
    [self addChildViewController:tool];
    self.tool=tool;
    return self.tool;
}

- (void)alertView:(NSString *)key index:(int)index{
    void(^block)(int buttonIndex)=[self.blocks objectForKey:key];
    if(block){
        block(index);
    }
    
}

- (BOOL)showPopAction{
    return NO;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    NSString *key=[NSString stringWithFormat:@"%u",[alertView hash]];
    [[SgrGCD sharedInstance] enqueueForeground:^{
        void(^block)(int buttonIndex)=[self.blocks objectForKey:key];
        if(block){
            block(buttonIndex);
        }
    }];
    
    //    void(^block)(int buttonIndex)=[self.blocks objectForKey:[NSString stringWithFormat:@"%u",[alertView hash]]];
    //    if(block){
    //        block(buttonIndex);
    //    }
}



- (void)openShare:(NSDictionary *)dic{
    
    self.isShareShow=YES;
    self.mark=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.mark setBackgroundColor:[UIColor blackColor]];
    self.mark.alpha=0.6;
    self.mark.frame=self.view.bounds;
    [self.view addSubview:self.mark];
    __weak typeof(self) me=self;
    [self.mark handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        
        [UIView animateWithDuration:0.2 animations:^{
//            me.share.view.frame=CGRectMake(0, GlobleHeight, GlobleWidth, 177.f);
//            [me.share cancelAnimation];
            [me.share dropAnimation];
        } completion:^(BOOL finished) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenAnimation) name:@"shareViewDisappear" object:nil];
            
        }];
       
    }];
    
//    self.share=[[CLShareViewController alloc] initWithNibName:@"CLShare" bundle:nil];
    self.share=[[CLShareViewController alloc] init];
   
    self.share.view.frame=CGRectMake(0, GlobleHeight, GlobleWidth, 177.f);
    [self.view addSubview:self.share.view];
    [UIView animateWithDuration:0.2 animations:^{
        self.share.view.frame=CGRectMake(0, GlobleHeight-177, GlobleWidth, 177.f);
    }];
    
  
        self.share.qq.hidden=![QQApiInterface isQQInstalled];
    self.share.qqLable.hidden=![QQApiInterface isQQInstalled];
    
    
    [self.share.cancle handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [UIView animateWithDuration:0.2 animations:^{
//            me.share.view.frame=CGRectMake(0, GlobleHeight, GlobleWidth, 177.f);
//            [self.share cancelAnimation];
            [me.share dropAnimation];
        } completion:^(BOOL finished) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenAnimation) name:@"shareViewDisappear" object:nil];
            
        }];
    }];
    
    
    [self.share.weixin handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        
        [me.share.view removeFromSuperview];
        [me.mark removeFromSuperview];
        me.share=nil;
        me.mark=nil;
       
        [[CLGlobleDataModel sharedInstance] share2Wechat:[dic sgrGetType:[UIImage class] forKey:@"icon"]
                                                   title:[dic sgrGetStringForKey:@"title"]
                                                 content:[dic sgrGetStringForKey:@"content"]
                                                     url:[dic sgrGetStringForKey:@"url"]
                                              captureImg:[dic sgrGetType:[UIImage class] forKey:@"image"]
                                                 uiBlock:^(BOOL success, NSString *message) {
                                                      me.isShareShow=NO;
                                                     if(success){
                                                         [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"分享成功"];
                                                     }else{
                                                         [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:message];
                                                     }
        }];
    }];
    
    
    [self.share.pengyou handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me.share.view removeFromSuperview];
        [me.mark removeFromSuperview];
        me.share=nil;
        me.mark=nil;
       
        [[CLGlobleDataModel sharedInstance] share2pengyou:[dic sgrGetType:[UIImage class] forKey:@"icon"]
                                                   title:[dic sgrGetStringForKey:@"title"]
                                                 content:[dic sgrGetStringForKey:@"content"]
                                                     url:[dic sgrGetStringForKey:@"url"]
                                              captureImg:[dic sgrGetType:[UIImage class] forKey:@"image"]
                                                 uiBlock:^(BOOL success, NSString *message) {
                                                     me.isShareShow=NO;
                                                     if(success){
                                                         [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"分享成功"];
                                                     }else{
                                                         [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:message];
                                                     }
                                                 }];
    }];
    
    [self.share.qq handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me.share.view removeFromSuperview];
        [me.mark removeFromSuperview];
        me.share=nil;
        me.mark=nil;
        
        [[CLGlobleDataModel sharedInstance] share2QQ:nil
                                               title:[dic sgrGetStringForKey:@"title"]
                                             content:[dic sgrGetStringForKey:@"content"]
                                                 url:[dic sgrGetStringForKey:@"url"]
                                        captureImage:[dic sgrGetType:[UIImage class] forKey:@"image"]
                                            thumbImg:[dic sgrGetType:[UIImage class] forKey:@"icon"]
                                             uiBlock:^(BOOL success, NSString *message) {
                                                 me.isShareShow=NO;
                                                     if(success){
                                                         [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"分享成功"];
                                                     }else{
                                                         [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:message];
                                                     }
        }];
    }];
    
    [self.share.sina handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me.share.view removeFromSuperview];
        [me.mark removeFromSuperview];
        me.share=nil;
        me.mark=nil;
        [[CLGlobleDataModel sharedInstance] share2Sina:[dic sgrGetStringForKey:@"title"]
                                                   url:[dic sgrGetStringForKey:@"url"]
                                            controller:(UIViewController *)[self k_currentController]
                                          captureImage:[dic sgrGetType:[UIImage class] forKey:@"image"]
                                               uiBlock:^(BOOL success, NSString *message) {
                                                   me.isShareShow=NO;
//                                                   if(success){
//                                                       [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"分享成功"];
//                                                   }else{
//                                                       [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:message];
//                                                   }
                                               }];
    }];
}

- (void)hiddenAnimation{
    [UIView animateWithDuration:0.2 animations:^{
        self.share.view.frame=CGRectMake(0, GlobleHeight, GlobleWidth, 177.f);
        [self.share.view removeFromSuperview];
        [self.mark removeFromSuperview];
        self.share=nil;
        self.mark=nil;
        self.isShareShow=NO;
        
    } completion:^(BOOL finished) {  
        
    }];
}


- (void)startLoading{
    __weak typeof(self) me=self;
    sgrSafeMainThread(^{
        me.theActive=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        me.theActive.frame=CGRectMake(0, 0, 45.f, 45.f);
        [me.theActive setCenter:CGPointMake(me.view.frame.size.width/2.f, me.view.frame.size.height/2.f)];
        [me.view addSubview:self.theActive];
        [me.theActive startAnimating];
    })
    
    

}

- (void)stopLoading{
    __weak typeof(self) me=self;
    sgrSafeMainThread(^{
        [me.theActive stopAnimating];
        [me.theActive removeFromSuperview];
        me.theActive=nil;
    })
   
}

////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark --UCChangeUserHeaderMenuViewDelegate
- (void)userSelectPicWithType:(UIImagePickerControllerSourceType)sourceType result:(void(^)(UIImage* image))block
{
    self.pickblock = block;
    //self.ucm=nil;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"设备不支持"];
        return;
    }
    // NSLog(@"%s",__PRETTY_FUNCTION__);
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    pickerController.allowsEditing = YES;
    pickerController.sourceType = sourceType;
    [self presentModalViewController:pickerController animated:YES];
}


- (void)userSelectPicWithType2:(UIImagePickerControllerSourceType)sourceType result:(void(^)(UIImage* image))block
{
    self.pickblock = block;
    //self.ucm=nil;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"设备不支持"];
        return;
    }
    // NSLog(@"%s",__PRETTY_FUNCTION__);
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    pickerController.allowsEditing = NO;
    pickerController.sourceType = sourceType;
    [self presentModalViewController:pickerController animated:YES];
}

#pragma mark -
#pragma mark --UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSString *mediaType = [info sgrGetStringForKey:UIImagePickerControllerMediaType];
    // 默认只能看到图片，这个可以不考虑
    if ([mediaType isEqualToString:((NSString *)kUTTypeMovie)]) {
        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"不支持类型"];

        // 警告，用户不能选择视频、音频
        return;
    }
    
    
    UIImage *userSelectedHeaderImage = [info sgrGetType:[UIImage class] forKey:UIImagePickerControllerOriginalImage];
    if (picker.allowsEditing) {
        userSelectedHeaderImage = [info sgrGetType:[UIImage class] forKey:UIImagePickerControllerEditedImage];
    }
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(userSelectedHeaderImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
    
    
    [self dismissViewControllerAnimated:YES completion:^(void){
        
    }];
    
    if (self.pickblock != NULL)
        self.pickblock(userSelectedHeaderImage);
    self.pickblock=NULL;
    //[self __photoGet:userSelectedHeaderImage];
    // 用Data换取URL地址
    //[_userModel exchangeURLWithImage:self.userSelectedHeaderImage];
}

- (void)__photoGet:(UIImage *)image{
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSString * message = [error description];
    if ([message length]==0) {
        // 用户锁拍着照片保存成功
    }
    else{
        // 用户锁拍摄照片保存失败
    }
}


@end
